import { Request, RequestHandler, Response } from "express";
import {
  IGetUserByIdReq,
  IAddUserReq,
  IUpdateUserReq,
  IDeleteUserReq,
  IGetUserByEmployeeIdReq,
  IGetUserByTokenReq
} from "../../models/user.model";
import * as UserService from "../services/user.service";
import * as UserRolesService from "../services/user-roles.service";
import * as RolesService from "../services/role.service";
import * as PermissionsService from "../services/permission.service";
import * as ProjectService from "../services/project.service";
import fs from "fs";
import { IncomingForm } from "formidable";
import bcrypt from "bcrypt";

/**
 * Get active user records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getUsers: RequestHandler = async (req: Request, res: Response) => {
  try {
    const users = await UserService.getUsers();

    res.status(200).json({
      data: users,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[users.controller][getUsers][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "用户信息列表获取失败！",
    });
  }
};

/**
 * Get user record based on id provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getUserById: RequestHandler = async (
  req: IGetUserByIdReq,
  res: Response
) => {
  try {
    const user = await UserService.getUserById(req.params.id);

    res.status(200).json({
      data: user,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[users.controller][getUserById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "用户信息获取失败！",
    });
  }
};

/**
 * Get user record based on token provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getUserByToken: RequestHandler = async (
  req: IGetUserByTokenReq,
  res: Response
) => {
  try {
    const user = await UserService.getUserByToken(req.params.userToken);
    const roles = await RolesService.getRolesByIds(JSON.parse(user[0].userRoles.toString()));
    const permissionSet = new Set();
    const roleNameList: string[] = [];
    roles.forEach((role) => {
      roleNameList.push(role.roleName);
      JSON.parse(role.rolePermissions.toString()).forEach(permissionSet.add, permissionSet);
    })
    const permissionList = await PermissionsService.getPermissionsByIds(Array.from(permissionSet) as number[]);
    const ownedProjects = await ProjectService.getProjectsByOwnerId(user[0].id);

    const userInfo = {
      id: user[0].id,
      name: user[0].userName,
      avatar: user[0].userPhotoPath,
      roles: roleNameList,
      permissions: permissionList,
      projects: ownedProjects
    }

    res.status(200).json({
      data: userInfo,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[users.controller][getUserById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "用户信息获取失败！",
    });
  }
};

/**
 * Get user record based on email provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getUserByEmployeeId: RequestHandler = async (
  req: IGetUserByEmployeeIdReq,
  res: Response
) => {
  try {
    const user = await UserService.getUserByEmployeeId(req.params.employeeId);

    res.status(200).json({
      data: user,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[users.controller][getUserByEmployeeId][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "用户信息获取失败！",
    });
  }
};

/**
 * Inserts a new user record
 *
 * @param req Express Request
 * @param res Express Response
 */
export const addUser: RequestHandler = async (
  req: IAddUserReq,
  res: Response
) => {
  try {
    req.body.createdTime = new Date(Date.now());
    req.body.updatedTime = req.body.createdTime;
    req.body.userBirthday = req.body.userBirthday
      ? new Date(req.body.userBirthday).toISOString().slice(0, 10)
      : null;
    let roleList = req.body.userRoles;
    req.body.userRoles = req.body.userRoles?.length > 0? JSON.stringify(req.body.userRoles) : "";
    // if(req.body.userPassword) {
    //   await bcrypt.hash(req.body.userPassword, 10).then(function(hash) {
    //     // Store hash in your password DB.
    //     req.body.userPassword = hash;
    //  });
    // }
    delete req.body['isUpdatePassword'];

    const result = await UserService.insertUser(req.body);

    if (roleList?.length > 0 && result) {
      const user = await UserService.getUserByEmployeeId(
        req.body.employeeId
      );
      let user_roles = roleList.map(
        (item: number) => {
          return [
            user[0].id,
            item,
          ];
        }
      );
      await UserRolesService.insertUserRoles(
        user_roles
      );
    }

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[users.controller][addUser][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    if (error.code === "ER_DUP_ENTRY") {
      res.status(500).json({
        message: "邮箱地址或身份证号已存在！",
      });
    } else {
      res.status(500).json({
        message: "用户信息保存失败！",
      });
    }
  }
};

/**
 * Updates existing user record
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const updateUserById: RequestHandler = async (
  req: IUpdateUserReq,
  res: Response
) => {
  try {
    req.params.id = req.params.id;
    req.body.updatedTime = new Date(Date.now());
    req.body.userBirthday = req.body.userBirthday
      ? req.body.userBirthday.length === 10 ?req.body.userBirthday : new Date(req.body.userBirthday).toISOString().slice(0, 10)
      : null;
    let roleList = req.body.userRoles;
    req.body.userRoles = req.body.userRoles?.length > 0? JSON.stringify(req.body.userRoles) : "";
    // if(req.body.isUpdatePassword && req.body.userPassword) {
    //   bcrypt.hash(req.body.userPassword, 10).then(function(hash) {
    //     // Store hash in your password DB.
    //     req.body.userPassword = hash;
    //  });
    // }
    delete req.body['isUpdatePassword'];

    const result = await UserService.updateUser({
      ...req.body,
      id: req.params.id,
    });

    if (roleList?.length > 0 && result){
      let user_roles = roleList.map(
        (item: number) => {
          return [
            req.params.id,
            item,
          ]
          }
      );
  
      await UserRolesService.deleteUserRoles(
        req.params.id
      );
      await UserRolesService.insertUserRoles(
        user_roles
      );
    }

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[users.controller][updateUserById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    if (error.code === "ER_DUP_ENTRY") {
      res.status(500).json({
        message: "邮箱地址或身份证号已存在！",
      });
    } else {
      res.status(500).json({
        message: "用户信息失败！",
      });
    }
  }
};

/**
 * deletes a user
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const deleteUserById: RequestHandler = async (
  req: IDeleteUserReq,
  res: Response
) => {
  try {
    await UserRolesService.deleteUserRoles(
      req.params.id
    );
    const result = await UserService.deleteUser(req.params.id);

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[users.controller][deleteUserById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "用户信息删除失败！",
    });
  }
};

/**
 * deletes a user
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const upload: RequestHandler = async (req: any, res: Response) => {
  try {
    console.log(req);
    let info = { status: "0", message: "上传头像成功", srcurl: "" };
    // 初始化处理文件对象
    var form = new IncomingForm();
    form.parse(req, function (error, fields, files) {
      if (error) {
        info.status = "1";
        info.message = "上传头像失败";
        res.send(info);
      }

      const folderPath = 'public/profile/';
      if (!fs.existsSync(folderPath)) {
        fs.mkdirSync(folderPath);
      }
      const fullName = `${folderPath}${Date.now().toString()}_${files.file[0].originalFilename}`;
      fs.writeFileSync(
        `${fullName}`,
        fs.readFileSync(files.file[0].filepath)
      ); // 存储图片到public静态资源文件夹下
      info.srcurl=fullName;
      res.send(info);
    });
  } catch (error) {
    console.error(
      "[users.controller][deleteUserById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "用户头像上传失败！",
    });
  }
};
